package com.sm.healthy.ui.fragment

import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.sm.healthy.R
import com.sm.healthy.base.BaseFragment
import com.sm.healthy.base.handle.TopHandle
import com.sm.healthy.databinding.FragmentBloodoxygenBinding
import com.sm.healthy.device.MedicalProtocol
import com.sm.healthy.device.interfaces.Up_NBPListener
import com.sm.healthy.event.SerialPortDataMsgEvent
import com.sm.healthy.model.BloodoxygenViewModel
import com.sm.healthy.ui.dialog.BloodOxygenDialog1
import com.sm.healthy.utils.SerialPortUtil
import kotlinx.android.synthetic.main.fragment_bloodoxygen.*
import kotlinx.android.synthetic.main.title_layout.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [BloodoxygenFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class BloodoxygenFragment : BaseFragment<BloodoxygenViewModel, FragmentBloodoxygenBinding>(),
    Up_NBPListener {

    private var bloodOxygenDialog1: BloodOxygenDialog1? = null

    /**
     * 协议解析
     */
    val medicalProtocol by lazy(LazyThreadSafetyMode.NONE) {
        MedicalProtocol().apply {
            setNbpListener(this@BloodoxygenFragment)
        }
    }

    override fun layoutId(): Int {
        return R.layout.fragment_bloodoxygen
    }

    private fun sendAction(action: Byte, param: Int) {
        val datas = medicalProtocol.NBP_Action(action.toInt(), param)
        SerialPortUtil.sendSerialPort(datas)
    }

    var isStart = false

    inner class Click {
        fun startMeasureBtn() {
            isStart = !isStart
            if (isStart) {
                startMeasure()
                mViewModel.startBtn.set("停止测量")
                mDatabind.tvBtnStart.setBackgroundResource(R.drawable.bg_btn_red_shape)
            } else {
                stopMeasure()
                stop()
            }
        }

        fun goHistory() {
            if (isStart) return mViewModel.toast.postValue("请先停止测量")
            nav().navigateAction(R.id.action_bloodoxygenFragment_to_historyDataFragment)
        }
    }

    private fun stop() {
        isStart = false
        mViewModel.startBtn.set("开始测量")
        mDatabind.tvBtnStart.setBackgroundResource(R.drawable.bg_btn_blue_shape)
    }

    /**
     * 开始测量
     */
    private fun startMeasure() {
        sendAction(MedicalProtocol.ACTION_CMD_NBP_START, 0)
        // TODO: 2022/1/3 开始测量
    }

    private fun stopMeasure() {
//        SerialPortUtil.closeSerialPort()
        sendAction(MedicalProtocol.ACTION_CMD_NBP_END, 0)
        // TODO: 2022/1/3 停止测量
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        mDatabind.handle = TopHandle(nav())
        iv_question.setOnClickListener {
            bloodOxygenDialog1 =
                activity?.let { it1 -> BloodOxygenDialog1(it1, R.style.BottomDialog) }
            bloodOxygenDialog1?.show()
        }
        mDatabind.bloodoxy = mViewModel
        mDatabind.click = Click()
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        medicalProtocol.setNbpListener(null)
        // TODO: 2022/1/3 没有停止测量应该要停止测量
        stopMeasure()
        super.onDestroyView()
    }

    /**
     * @param pressure 血压
     * 数据范围：0～300mmHg， -100代表无效值。
     */
    override fun onNBP_CuffPressure(pressure: Int) {
        if (pressure != -100)
            mViewModel.bloodValue.set(pressure.toString())
    }

    /**
     * 测量结束
     */
    override fun onNBP_End(end: Int) {
        stop()
        mViewModel.insert()
    }

    /**
     * @param systolic 收缩压
     * @param diastolic 舒张压
     * 0～300mmHg， -100代表无效值
     */
    override fun onNBP_Result(systolic: Int, diastolic: Int, count: Int) {
        lifecycleScope.launch(Dispatchers.Main) {
            if (systolic != -100) {
                mViewModel.bloodPressureEntity.value?.systolic = systolic
                mDatabind.tvSystolic.text = systolic.toString()
                when {
                    systolic <= 90 -> {
                        mViewModel.bloodPressureEntity.value?.levelSys = 1
                        mDatabind.tvFirst.changeLevel(1)
                    }
                    systolic in 91..139 -> {
                        mViewModel.bloodPressureEntity.value?.levelSys = 0
                        mDatabind.tvFirst.changeLevel(0)
                    }
                    systolic >= 140 -> {
                        mViewModel.bloodPressureEntity.value?.levelSys = 2
                        mDatabind.tvFirst.changeLevel(2)
                    }
                }
            }
            if (diastolic != -100) {
                mViewModel.bloodPressureEntity.value?.diastolic = diastolic
                mDatabind.tvDiastolic.text = diastolic.toString()
                when {
                    diastolic <= 60 -> {
                        mViewModel.bloodPressureEntity.value?.levelDia = 1
                        mDatabind.tvSecond.changeLevel(1)
                    }
                    diastolic in 60..89 -> {
                        mViewModel.bloodPressureEntity.value?.levelDia = 0
                        mDatabind.tvSecond.changeLevel(0)
                    }
                    diastolic >= 90 -> {
                        mViewModel.bloodPressureEntity.value?.levelDia = 2
                        mDatabind.tvSecond.changeLevel(2)
                    }
                }
            }
        }
    }

    /**
     * @param pulseRate
     * 脉率 0～255BPM，-100代表无效值
     */
    override fun onNBP_Result(pulseRate: Int) {
        mViewModel.toast.postValue("脉率:$pulseRate")
        lifecycleScope.launch(Dispatchers.Main) {
            if (pulseRate != -100) {
                mViewModel.bloodPressureEntity.value?.pulseRate = pulseRate
                mDatabind.tvPulseRate.text = pulseRate.toString()
                when {
                    pulseRate <= 60 -> {
                        mViewModel.bloodPressureEntity.value?.levelSys = 1
                        mDatabind.tvThird.changeLevel(1)
                    }
                    pulseRate in 60..99 -> {
                        mViewModel.bloodPressureEntity.value?.levelSys = 0
                        mDatabind.tvThird.changeLevel(0)
                    }
                    pulseRate >= 100 -> {
                        mViewModel.bloodPressureEntity.value?.levelSys = 2
                        mDatabind.tvThird.changeLevel(2)
                    }
                }
            }
        }
    }

    /**
     * 血压状态 暂时可不管
     */
    override fun onNBP_State(state: ByteArray?) {

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onGetMsg(serialPortDataMsgEvent: SerialPortDataMsgEvent) {
        when (serialPortDataMsgEvent.action) {
            SerialPortUtil.ACTION_SERIAPORT_READ -> {
                val data: ByteArray = serialPortDataMsgEvent.data
                val size: Int = serialPortDataMsgEvent.size
                medicalProtocol.Resolve(data, 0, size)
            }
        }
    }

}